package com.kaisu.blog.domain.blog;

import cn.hutool.core.bean.BeanUtil;
import com.kaisu.blog.common.exceptions.InternalException;
import com.kaisu.blog.common.util.IdUtils;
import com.kaisu.blog.domain.blog.command.BlogCreateCommand;
import com.kaisu.blog.domain.blog.enums.BlogStatus;
import com.kaisu.blog.domain.file.File;
import com.kaisu.blog.domain.user.User;
import lombok.Data;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author kaisu
 */
@Data
public class Blog {
    /**
     * id
     */
    private String id;
    /**
     * 标题
     */
    private String title;
    /**
     * 封面
     */
    private File cover;
    /**
     * 内容
     */
    private String content;
    /**
     * 状态
     */
    private BlogStatus status;
    /**
     * 创建用户
     */
    private User createUser;
    /**
     * 最后更新时间
     */
    private LocalDateTime lastModifyTime;
    /**
     * 发布时间
     */
    private LocalDateTime publishedTime;
    /**
     * 点赞
     */
    private Set<Like> likes;
    /**
     * 评论
     */
    private List<Comment> comments;

    public static Blog create(BlogCreateCommand command, User user) {
        Blog blog = new Blog();
        blog.init();
        blog.setId(IdUtils.generateId());
        BeanUtil.copyProperties(command, blog);
        blog.setCreateUser(user);
        return blog;
    }

    private void init() {
        setStatus(BlogStatus.PENDING);
        setLikes(new HashSet<>());
        setLastModifyTime(LocalDateTime.now());
        setComments(new ArrayList<>());
    }

    public void updateTitle(String title, User operate) {
        checkAuth(operate);
        this.title = title;

    }

    public void checkAuth(User operate) {
        if (!operate.equals(createUser)) {
            throw new InternalException("系统异常！");
        }
    }

    public void editConent(String content, User operate) {
        this.setContent(content);
    }

    public void published(User operate) {
        checkAuth(operate);
        this.setStatus(BlogStatus.PUBLISHED);
        this.setPublishedTime(LocalDateTime.now());
    }

    public void appendComment(Comment comment) {
        this.getComments().add(comment);
    }

    public void like(User user) {
        if (this.getLikes().contains(Like.create(user, this))) {
            throw new InternalException("不能重复点赞！");
        }
        this.getLikes().add(Like.create(user, this));
    }

    public void unLike(User user) {
        this.getLikes().remove(Like.create(user, this));
    }
}
